<template>
  <div>
    <div class="bgfff mtrbl20 ptrbl20 nopb20">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="客户企业" prop="companyId">
            <el-select v-model="queryParams.companyId" placeholder="请选择客户企业" clearable size="medium" filterable>
              <el-option
                v-for="dict in companyTreeSelect"
                :key="dict.id"
                :label="dict.companyName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="公众号名称" prop="appName" label-width="85px">
            <el-input
              v-model="queryParams.appName"
              placeholder="请输入公众号名称"
              clearable
              size="medium"
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="medium" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" plain icon="el-icon-plus" size="medium" @click="handleAdd" v-hasPermi="['offiaccount:public:add']">新增公众号</el-button>
           </el-form-item>
        </el-form>
        </el-col>
        </el-row>
      </div>
      <div class="app-container">  
        <el-row :gutter="20">
          <!--用户数据-->
          <el-col :span="24" :xs="24">
          <el-table v-loading="loading" :data="publicList">
          
          <el-table-column label="序号" prop="" width="55" align="center">
            <template slot-scope="scope">
              <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="公众号名" align="left" key="appName" prop="appName"/>
          <el-table-column label="appId" align="left" key="appId" prop="appId"/>
          <el-table-column label="所属企业" align="left" key="companyName" prop="companyName" width="280"/>
          <el-table-column label="邮件发送状态" align="left" :formatter="mailStatusFormat"/>
          <el-table-column label="安装配置状态" align="left" :formatter="buildStatusFormat"/>
          <!-- <el-table-column label="删除状态" align="left" :formatter="isDeleteFormat"/> -->
          <el-table-column label="关注的用户人数" align="left" prop="userCount"/>
          <el-table-column label="创建时间" align="left" key="createTime" prop="createTime"/>
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <!-- <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button size="small" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看详情</el-button>
              <el-button size="medium" type="text" icon="el-icon-eleme" @click="handleSend(scope.row)">发送邮件</el-button>
              <el-button size="small" type="text" icon="el-icon-finished" @click="handleBuild(scope.row)">完成配置</el-button>
              <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button> -->
              <el-dropdown size="mini" split-button type="primary" @click="handleView(scope.row)" placement="bottom-start" trigger="click">
                详 情
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item icon="el-icon-edit" v-hasPermi="['offiaccount:public:edit']"  @click.native="handleUpdate(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-delete" v-hasPermi="['offiaccount:public:delete']" :disabled="scope.row.isDelete==true" @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-eleme" v-hasPermi="['offiaccount:public:sendEmail']" :disabled="scope.row.mailStatus==1" @click.native="handleSend(scope.row)">发送邮件</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-finished" v-hasPermi="['offiaccount:public:buildStatus']" :disabled="scope.row.buildStatus==1" @click.native="handleBuild(scope.row)">完成配置</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-s-unfold" v-hasPermi="['offiaccount:public:fileSaveToRemote']" @click.native="handleSaveToRemote(scope.row)">转存txt文件</el-dropdown-item>

                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="170px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="公众号名称：" prop="appName"
            :rules="{
              required: true, message: '公众号名称不能为空', trigger: 'blur'
            }">
              <el-input v-model="dynamicValidateForm.appName" placeholder="请输入公众号名称" clearable/>
            </el-form-item>
          </el-col>
         
          <el-col :span="24">
            <el-form-item label="公众号appId：" prop="appId"
            :rules="{
              required: true, message: '公众号appId不能为空', trigger: 'blur'
            }">
              <el-input v-model="dynamicValidateForm.appId" placeholder="请输入公众号appId" clearable :disabled="dynamicValidateForm.id != undefined"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="appSecret密钥：" prop="appSecret"
            :rules="{
              required: true, message: 'appSecret密钥不能为空', trigger: 'blur'
            }">
              <el-input v-model="dynamicValidateForm.appSecret" placeholder="请输入appSecret密钥" clearable :disabled="dynamicValidateForm.id != undefined"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属企业：" prop="companyId"
            :rules="{
              required: true, message: '所属企业不能为空', trigger: 'blur'
            }">
              <el-select v-model="dynamicValidateForm.companyId" filterable clearable placeholder="请选择所属企业" style="width: 100%;">
                <el-option
                  v-for="item in companyTreeSelect"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item
            v-for="(email, index) in dynamicValidateForm.emails"
            :label="'邮箱' + index"
            :key="email.key"
            :prop="'emails.' + index + '.value'"
            :rules="[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ]">
            <el-input v-model="email.value" style="width:85%"></el-input>
            <el-button  style="width:15%" @click.prevent="removeDomain(email)" size="medium" type="text" icon="el-icon-remove">删除</el-button>
          </el-form-item>
          </el-col>
          <el-col :span="24">
              <el-form-item>
              <el-button @click="addDomain" plain icon="el-icon-circle-plus" style="border: 1px dashed #dcdfe6;">新增邮箱</el-button>
              </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="上传安全域名txt文件：" prop="txtFile"
            >
              <el-upload
              v-model="dynamicValidateForm.txtFile"
              ref="upload"
              action="#"
              :auto-upload="false"
               accept=".txt"
               :on-remove="remove"
              :on-change="onChange"
              :before-upload="beforeUploadFile"
               multiple
              :limit="1" 
              >
                　<el-button
              　　　　slot="trigger"
              　　　　size="small"
              　　　　icon="el-icon-upload"
              　　>选择上传文件
              　　</el-button>
              　　<div slot="tip" class="el-upload__tip">
              　　　　　只能上传txt文件，且不超过200kb
              　　 </div>
              </el-upload>

            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dynamicValidateForm.id != undefined">
            <el-form-item label="跳转url：" prop="jumpUrl">
              <el-input v-model="dynamicValidateForm.jumpUrl" placeholder="请输入跳转url" clearable :disabled="dynamicValidateForm.id != undefined"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮箱：" prop="emails"> 
              <el-tag
              :key="index"
              v-for="(tag,index) in dynamicValidateForm.emails"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)">
              {{tag}}
            </el-tag>
            <el-input
              style="width:150px;"
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button v-else size="small" class="button-new-tag"  @click="showInput" icon="el-icon-circle-plus">添加</el-button>
            </el-form-item>

          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button> -->
        
        <el-button type="primary" @click="submitForm1('dynamicValidateForm')" v-preventReClick>提交</el-button>
        <el-button @click="cancel">取 消</el-button>
         <!-- <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button> -->
        <!-- <el-button @click="resetForm('dynamicValidateForm')">重置</el-button> -->

      </div>
    </el-dialog>

  </div>
  </div>
</template>

<script>
import { publicList, getCompanyTreeSelect, offiaccountSendEmail, offiaccountBuildStatus, saveToRemote, offiaccountDelete, offiaccountListAdd ,offiaccountListEdit, offiaccountListInfo } from "@/api/offiaccount/public";
export default {
  name: "Public",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      formData: "",
      inputVisible: false,
      inputValue: '',
      dynamicValidateForm: {
         emails: [],
         appName:'',
         appId:'',
         appSecret:'',
         companyId:'',
         txtFile: ''
      },
      // 用户表格数据
      publicList: null,
       // 客户企业全部下拉列表
      companyTreeSelect:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        companyId: undefined,
        appName: undefined
      },
      // 表单校验
      // rules: {
      //   appName: [
      //     { required: true, message: "公众号名称不能为空", trigger: "blur" }
      //   ],
      //   appId: [
      //     { required: true, message: "公众号appId不能为空", trigger: "blur" }
      //   ],
      //   appSecret: [
      //     { required: true, message: "公众号密钥不能为空", trigger: "blur" }
      //   ],
      //   companyId: [
      //     { required: true, message: "客户企业不能为空", trigger: "change" }
      //   ]
      // },
    };
  },
  created() {
    this.getList();
    getCompanyTreeSelect().then(response => {
          this.companyTreeSelect = response.data;
        }
      );
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      publicList(this.queryParams).then(response => {
          this.publicList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 性别状态翻译
    mailStatusFormat(row) {
      let mailStatus = row.mailStatus;
      switch (mailStatus) {
        case 0:
        mailStatus = "未发送";
          break;
        case 1:
        mailStatus = "已发送";
          break;
      }
      return mailStatus;
    },
    // 状态字典翻译
    buildStatusFormat(row) {
      let buildStatus = row.buildStatus;
      switch (buildStatus) {
        case 0:
        buildStatus = "未配置";
          break;
        case 1:
        buildStatus = "已配置";
          break;
      }
      return buildStatus;
    },
    // isDeleteFormat(row) {
    //   let isDelete = row.isDelete;
    //   switch (isDelete) {
    //     case false:
    //     isDelete = "未删除";
    //       break;
    //     case true:
    //     isDelete = "已删除";
    //       break;
    //   }
    //   return isDelete;
    // },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      //this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.dynamicValidateForm = {
        id: undefined,
        appName: undefined,
        appId: undefined,
        appSecret: undefined,
        companyId: undefined,
        txtFile: undefined,
        jumpUrl: undefined,
        emails: []
      };
      this.resetForm("dynamicValidateForm");
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建公众号";
    },
     /** 编辑按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      offiaccountListInfo(id).then(response => {
        this.dynamicValidateForm = response.data;
        // this.companyOptions = response.data.companies;
        // this.roleOptions = response.data.roles;
       //this.dynamicValidateForm.emails = response.data.swmMailList;

        this.open = true;
        this.title = "编辑公众号";
      });
    },
    handleView(row) {
      const id = row.id;
      const appid = row.appId;
      this.$router.push("/public/details/" + id + '/' +appid);
    },
    handleSend(row) {
      const id = row.id;
      this.$confirm('是否确认已发送邮件?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return offiaccountSendEmail(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("确认成功");
        }).catch(function() {});
    },
    handleBuild(row) {
      const id = row.id;
      this.$confirm('是否确认已完成配置?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return offiaccountBuildStatus(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("确认成功");
        }).catch(function() {});
    },

    handleSaveToRemote(row) {
      const id = row.id;
      this.$confirm('是否确认转存txt文件至静态资源服务器?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return saveToRemote(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("转存txt文件至服务器成功");
        }).catch(function() {});
    },


    handleDelete(row) {
      const id = row.id;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return offiaccountDelete({id:id});
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
     beforeUploadFile(file) {
      //console.log(file)
      const size = file.size / 1024 / 1024
      if(size > 200) {
        this.$notify.warning({
          title: '警告',
          message: `文件大小不得超过200M`
        });
      }
    },
    //删除图片
    remove(file) {
      // console.log(file);
      for (let i = 0; i < this.dynamicValidateForm.txtFile.length; i++) {
        if (file === this.dynamicValidateForm.txtFile[i]) {
          this.dynamicValidateForm.txtFile.splice(i, 1);
        }
      }
    },
    onChange(file, fileList) {
      console.log(file, fileList);
      //console.log(fileList)
      this.dynamicValidateForm.txtFile = file.raw;
      //console.log(this.dynamicValidateForm);
    },
    submitForm1(formName){
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = new FormData();
          for (var key in that.dynamicValidateForm) {
            formData.append(key, that.dynamicValidateForm[key]);
            //console.log(formData.get(key));
          }
          that.formData = formData;

          if(that.dynamicValidateForm.txtFile){
            if (that.dynamicValidateForm.id != undefined) {
              offiaccountListEdit(that.formData).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              }).catch(()=>{});
            }else{
              offiaccountListAdd(that.formData).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              }).catch(()=>{});
            }
            this.$refs.upload.clearFiles()
          }else{
            this.$message.error('请选择上传安全域名txt文件');
          }
        } else {
          //console.log('error submit!!');
          return false;
        }
      });
    },
    handleClose(tag) {
        //alert(this.dynamicValidateForm.emails);
        this.dynamicValidateForm.emails.splice(this.dynamicValidateForm.emails.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
          if(this.dynamicValidateForm.emails.length<3){
            this.dynamicValidateForm.emails.push(inputValue);
          }else{
            this.$message.error('邮箱最多可设置3个！')
          }
      }
      this.inputVisible = false;
      this.inputValue = '';
    }
  }
};
</script>
<style scoped lang="scss">
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>